import { WebGLComponent } from '../../core/webgl';
import { Color, ArrayHelper } from '../../core/util';

export class S04 extends WebGLComponent {
    static desc = '索引缓冲区';
    protected vs: string = `
        attribute vec3 a_Position;
        void main() {
            gl_Position = vec4(a_Position,1.0);
        }
    `;
    protected fs: string = `
        void main() {
            //设置颜色
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
        }
    `;
    protected arrData: number[][] = [
        [-0.5, 0.5, 0.0],
        [0.5, 0.5, 0.0],
        [0.5,-0.5,0.0],
        [-0.5,-0.5,0.0]
    ]
    protected indexData: number[][] = [
        [0,1,2],
        [0,2,3]
    ]
    protected indexBuf: number[] = [];

    public renderWebGl() {
        this.clear();
        let program = this.createProgram(this.vs, this.fs);
        this.bindBuffer();
        this.bindVertex(program);
        // this.gl.drawArrays(this.gl.TRIANGLES,0, 3);
        this.gl.drawElements(this.gl.TRIANGLES, 6, this.gl.UNSIGNED_BYTE, 0);
    }
    protected bindVertex(program: WebGLProgram) {
        //获取坐标点
        var a_Position = this.gl.getAttribLocation(program, 'a_Position');
        //将缓冲区对象分配给a_Position变量

        this.gl.vertexAttribPointer(a_Position, 3, this.gl.FLOAT, false, 4 * 3, 0);
        //连接a_Position变量与分配给它的缓冲区对象
        this.gl.enableVertexAttribArray(a_Position);
    }
    protected bindBuffer() {

        let indexBuf = this.gl.createBuffer();
        this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, indexBuf);
        // 索引为无符号短整型 2个字节 2^16
        this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(ArrayHelper.reshape(this.indexData)), this.gl.STATIC_DRAW);

        let dataBuf = this.gl.createBuffer();
        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, dataBuf);
        this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(ArrayHelper.reshape(this.arrData)), this.gl.STATIC_DRAW);

    }
}